import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getAuthToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  async config => {
    config.headers['Content-Type'] = 'application/json'
    if (config.headers['No-Token']) { // 不需携带token
      return config
    }
    const authToken = getAuthToken()
    if (!authToken) {
      await store.dispatch('accounts/refreshToken')
    }
    // let each request carry token
    // ['X-Token'] is a custom headers key
    // eslint-disable-next-line require-atomic-updates
    config.headers['Authorization'] = `Bearer ${getAuthToken()}`
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

const grant_type = 'Refresh-token'
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.type === 'ERROR') {
      const tempGrantType = response.config.headers['Grant-type']
      if (tempGrantType && tempGrantType === grant_type) {
        res.message = '认证异常：刷新令牌过期'
      }
      Message({
        message: res.message || '哦！出错了怎么办',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(res)
    }
    if (res.type === 'UNAUTHORIZED') {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(res)
    }
    if (res.type === 'EXPIRE') {
      return new Promise((resolve, reject) => {
        store.dispatch('accnpmounts/refreshToken').then(() => {
          response.config.url = response.config.url.replace(response.config.baseURL, '')
          resolve(service.request(response.config))
        }).catch(error => {
          store.dispatch('accounts/resetLogin')
          reject(error)
        })
      })
    }

    if (res.data) {
      return Promise.resolve(res.data)
    } else {
      return Promise.resolve(res)
    }
  },
)

export default service
